<template>
  <div class="mt-1">
    <van-form>
      <h4 style="margin: 0 0 0.4rem 1rem; color: gray">
        当前产区:{{ this.$store.getters.productionLine }}
      </h4>
      <van-field
        readonly
        clickable
        name="picker"
        :value="FormulaCode"
        label="物料"
        placeholder="点击选择"
        @click="FormulaPicker = true"
      />
      <van-popup v-model="FormulaPicker" position="bottom">
        <van-picker
          show-toolbar
          value-key="DeviceName"
          :columns="columns"
          @confirm="FormulaConfirm"
          @cancel="FormulaPicker = false"
        />
      </van-popup>
      <van-field
        v-model="code"
        clearable
        label="拍码"
        ref="pmfocus"
        @focus="stopKeyborad"
        placeholder="请输入拍码"
      />
      <ag-grid-vue
        style="width: 100%; height: 62vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        :singleClickEdit="true"
        rowSelection="multiple"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <audio src="../../assets/warning.mp3" preload="auto" id="bgMusic"></audio>
    </van-form>
  </div>
</template>

<script>
import { AgGridVue } from "ag-grid-vue";
import { CODE_LENGTH } from "../../config";
import { mapGetters } from "vuex";
import { parseQRCode, toast } from "../../utils/common";
import { AgGrid } from "../../mixins/AgGrid";
import { commissionSubmit } from "../../api/feeding";
import { Picker } from "vant";
import { DeviceGive } from "../../api/feeding";
import { DeviceMaterial } from "../../api/feeding";

export default {
  name: "BOM",
  components: { AgGridVue, [Picker.name]: Picker },
  mixins: [AgGrid],
  data() {
    return {
      code: "",
      FormulaCode: "",
      columnDefs: [
        { headerName: "物料号", field: "ProductId", width: 90 },
        { headerName: "物料名称", field: "ProductName", width: 125 },
        { headerName: "生产日期", field: "ProductionDate", width: 100 },
        {
          headerName: "数量",
          field: "Num",
          width: 70,
        },
      ],
      rowData: [],
      FormulaPicker: false, //判断弹出
      columns: [], //放配料号
      SKUANndformulaData: [], //配方比的数组
    };
  },
  watch: {
    FormulaCode(val) {
      if (this.FormulaCode !== "") {
        this.SKUANndformulaData = [];
        this.SKUInfo(val);
      }
    },
    code(val) {
      if (val.length > CODE_LENGTH) {
        let res = parseQRCode(val);
        if (res) {
          this.findPat(res.palletNo, res.materialCode);
        } else {
          this.playMusic();
          toast("无法识别");
        }
      }
      this.code = "";
      this.$refs.pmfocus.focus();
    },
  },
  computed: {
    ...mapGetters(["productionLine"]),
  },
  methods: {
    // 消除获取焦点时自动弹出键盘
    stopKeyborad() {
      this.$refs.pmfocus.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.pmfocus.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    //播放警示音
    playMusic() {
      setTimeout(() => {
        let audio = document.getElementById("bgMusic");
        audio.play();
      }, 200);
    },
    async findPat(palletNo, materialCode) {
      if (!this.rowData.find((it) => it.UniqueId === palletNo)) {
        let user = this.$store.getters.user;
        let res = await commissionSubmit(
          this.productionLine,
          palletNo,
          materialCode,
          "2",
          user,
          "2",
          this.FormulaCode,
          this.$store.getters.WarehouseId
        );
        if (res && res.Status == 200 && res.Data) {
          this.rowData.push({
            ProductName: res.Data.ProductName,
            ProductId: res.Data.ProductId,
            UniqueId: res.Data.UniqueId,
            Num: res.Data.Num,
            ProductionDate: res.Data.ProductionDate.substring(0, 10),
            OutStorageBillDetailId: res.Data.OutStorageBillDetailId,
          });
        } else {
          this.playMusic();
          toast(res.Msg);
        }
      } else {
        this.playMusic();
        toast("此拍已被录入");
      }
    },
    //获取配方比号
    async getFormulaInfo() {
      let res = await DeviceGive("BOMFeeding", this.productionLine);
      console.log(res);
      if (res && res.data.Status == 200 && res.data.Data.length > 0) {
        this.columns = res.data.Data;
      } else {
        toast("无法获取设备选项，请联系管理员");
      }
    },
    //获取点击后的配方比号
    async SKUInfo(FormulaNum) {
      let res = await DeviceMaterial(
        this.productionLine,
        "BOMFeeding",
        FormulaNum
      );
      console.log(res);
      if (res.Status == 200) {
        if (res.Data.SKUItems.length > 0) {
          res.Data.SKUItems.map((it) => {
            let SKU = it.substring(0, it.indexOf(":"));
            this.SKUANndformulaData.push(SKU);
          });
        } else {
          toast("此物料没有配方比号");
        }
      } else {
        toast(res.Msg);
      }
    },
    FormulaConfirm(val) {
      console.log(val);
      this.FormulaCode = val.DeviceName;
      this.FormulaPicker = false;
      this.$refs.pmfocus.focus();
    },
    /*     saveNum(savevalue, sure) {
      this.savenum = savevalue;
      this.sureWIP = sure;
      this.submit();
    },
    canCel(sure) {
      this.sureWIP = sure;
    }, */
    /*     //提交，退回操作
    async submit() {
      let selectedData = this.gridApi.getSelectedRows();
      if (selectedData.length != 0) {
        this.saveValueVisible = true;
        if (this.sureWIP == true) {
          if (
            this.savenum == 0 ||
            this.savenum == "" ||
            this.savenum == undefined ||
            this.savenum == selectedData[0].Num
          ) {
            await EndPost(
              selectedData[0].OutStorageBillDeatilId,
              selectedData[0].UniqueId,
              selectedData[0].Num
            );
            //删除数组中的某个值
            let a = this.gridApi.updateRowData({ remove: selectedData });
            //删除rowData内此值
            let selectIndex = this.rowData.indexOf(a.remove[0]);
            this.rowData.splice(selectIndex - 1, 1);
            this.saveValueVisible = false;
            this.sureWIP = false;
          } else if (selectedData[0].Num < this.savenum) {
            this.savenum = selectedData[0].Num;
            toast("输入的数量已超出");
          } else if (selectedData[0].Num == this.savenum) {
            toast("请输入新的数据");
          } else {
            await EndPost(
              selectedData[0].OutStorageBillDeatilId,
              selectedData[0].UniqueId,
              Number(this.savenum)
            );
            //修改某个值
            selectedData[0].Num = this.savenum;
            this.gridApi.updateRowData({ updata: selectedData });
            this.saveValueVisible = false;
            this.sureWIP = false;
          }
        }
      } else {
        toast("未选择需要退回行");
      }
    }, */
  },
  mounted() {
    this.getFormulaInfo();
    this.$refs.pmfocus.focus();
  },
};
</script>
